#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Smart Diagnostic Workflow
AI-powered code quality diagnosis and reporting
"""
from __future__ import annotations

import json
import sys
from datetime import datetime
from pathlib import Path
from typing import Any

# Import from same directory
from ai_client import AIClient, AIProvider


class SmartDiagnosticWorkflow:
    """
    智能诊断工作流

    功能:
    - 读取错误日志
    - 调用 AI 进行诊断
    - 生成诊断报告
    - 保存到 reports 目录
    """

    def __init__(self, provider: AIProvider = AIProvider.MOCK) -> None:
        """
        Initialize diagnostic workflow

        Args:
            provider: AI provider to use
        """
        self.provider = provider
        self.client = AIClient(provider)
        self.reports_dir = Path("reports")
        self.reports_dir.mkdir(exist_ok=True)

    def run_full_diagnostic(
        self,
        error_log_path: str | Path = "reports/last_error.log",
    ) -> dict[str, Any]:
        """
        运行完整诊断流程

        Args:
            error_log_path: 错误日志文件路径

        Returns:
            诊断结果字典
        """
        print(f"[Diagnostic] Starting AI diagnostic workflow ({self.provider.value})...")

        # 1. Read error log
        error_log_path = Path(error_log_path)
        if not error_log_path.exists():
            return {
                "status": "error",
                "message": f"Error log not found: {error_log_path}",
            }

        with open(error_log_path, encoding="utf-8") as f:
            error_log = f.read()

        print(f"[Diagnostic] Read error log: {len(error_log)} characters")

        # 2. Call AI for diagnosis
        print("[Diagnostic] Calling AI for diagnosis...")
        diagnosis_result = self.client.diagnose_error(error_log)

        if diagnosis_result["status"] == "error":
            print(f"[Diagnostic] AI diagnosis failed: {diagnosis_result.get('error')}")
            return {
                "status": "error",
                "message": "AI diagnosis failed",
                "details": diagnosis_result,
            }

        # 3. Generate report
        report_file = self._generate_report(diagnosis_result, error_log)
        print(f"[Diagnostic] Report saved to: {report_file}")

        return {
            "status": "completed",
            "provider": self.provider.value,
            "report_file": str(report_file),
            "diagnosis": diagnosis_result,
        }

    def _generate_report(
        self,
        diagnosis: dict[str, Any],
        error_log: str,
    ) -> Path:
        """
        生成诊断报告

        Args:
            diagnosis: AI 诊断结果
            error_log: 原始错误日志

        Returns:
            报告文件路径
        """
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        report_file = self.reports_dir / f"ai_diagnostic_{timestamp}.md"

        with open(report_file, "w", encoding="utf-8") as f:
            f.write("# AI Diagnostic Report\n\n")
            f.write(f"**Generated:** {datetime.now().isoformat()}\n")
            f.write(f"**Provider:** {diagnosis.get('provider', 'unknown')}\n\n")

            f.write("## Diagnosis\n\n")
            f.write(f"{diagnosis.get('diagnosis', 'No diagnosis available')}\n\n")

            if "usage" in diagnosis:
                f.write("## API Usage\n\n")
                f.write(f"```json\n{json.dumps(diagnosis['usage'], indent=2)}\n```\n\n")

            f.write("## Original Error Log\n\n")
            f.write(f"```\n{error_log[:2000]}\n")
            if len(error_log) > 2000:
                f.write(f"\n... (truncated, total {len(error_log)} chars)\n")
            f.write("```\n")

        # Also save JSON version
        json_file = self.reports_dir / f"ai_diagnostic_{timestamp}.json"
        with open(json_file, "w", encoding="utf-8") as f:
            json.dump(
                {
                    "timestamp": datetime.now().isoformat(),
                    "provider": diagnosis.get("provider"),
                    "diagnosis": diagnosis,
                    "error_log_length": len(error_log),
                },
                f,
                indent=2,
                ensure_ascii=False,
            )

        return report_file


def main() -> int:
    """命令行入口"""
    import argparse

    parser = argparse.ArgumentParser(description="AI-powered code diagnostic tool")
    parser.add_argument(
        "--provider",
        choices=["openai", "anthropic", "mock"],
        default="mock",
        help="AI provider to use",
    )
    parser.add_argument(
        "--error-log",
        default="reports/last_error.log",
        help="Path to error log file",
    )

    args = parser.parse_args()

    # Map string to enum
    provider_map = {
        "openai": AIProvider.OPENAI,
        "anthropic": AIProvider.ANTHROPIC,
        "mock": AIProvider.MOCK,
    }

    provider = provider_map[args.provider]
    workflow = SmartDiagnosticWorkflow(provider=provider)

    result = workflow.run_full_diagnostic(error_log_path=args.error_log)

    if result["status"] == "completed":
        print(f"\n✅ Diagnostic completed successfully!")
        print(f"📄 Report: {result['report_file']}")
        return 0
    else:
        print(f"\n❌ Diagnostic failed: {result.get('message')}")
        return 1


if __name__ == "__main__":
    sys.exit(main())
